package com.example.app.controller;

import com.example.app.dto.ApiResponse;
import com.example.app.dto.FoodRecognitionResult;
import com.example.app.service.BaiduFoodRecognitionService;
import com.example.app.service.DeepSeekService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Mono;

import java.io.IOException;

@RestController
@RequestMapping("/api/food")
@RequiredArgsConstructor
public class FoodRecognitionController {

    private final BaiduFoodRecognitionService recognitionService;
    private final DeepSeekService deepSeekService;
    @PostMapping("/recognize")
    public ResponseEntity<ApiResponse<FoodRecognitionResult>> recognizeFood(
            @RequestParam("image") MultipartFile image) {
        try {
            FoodRecognitionResult result = recognitionService.recognizeFood(image);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(ApiResponse.error("识别失败: " + e.getMessage()));
        }
    }

    @PostMapping("/suggestion")
    public Mono<String> suggestionFood(
            @RequestParam Long userId,
            @RequestParam("image") MultipartFile image) throws IOException {
            FoodRecognitionResult result = recognitionService.recognizeFood(image);
        StringBuilder sb = new StringBuilder();

        if (result.getResult() != null && !result.getResult().isEmpty()) {
            FoodRecognitionResult.ResultItem item = result.getResult().get(0);
            sb.append("- ").append(item.getName());
            if (item.getHasCalorie()) {
                    sb.append("，卡路里：").append(item.getCalorie());
                }

                sb.append("\n");
        } else {
            sb.append("未识别到有效食物");
        }
        System.out.println("<UNK>" + sb.toString());
        String fullPrompt = deepSeekService.buildFoodPrompt(userId, sb.toString());
        return deepSeekService.answerQuestion(fullPrompt, false);

    }
//    @PostMapping("/answer")
//    public Mono<String> answerQuestion(
//            @RequestParam Long userId,
//            @RequestParam("image") MultipartFile image)
//    {
//        FoodRecognitionResult result = recognitionService.recognizeFood(image);
//        String fullPrompt = deepSeekService.buildPrompt(userId, message);
//        return deepSeekService.answerQuestion(fullPrompt, withRAG);
//    }
}